package com.guodi.model.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guodi.map.entity.MapDivision;
import com.guodi.model.dto.ApiDivisionToScoreValueDto;
import com.guodi.model.dto.ApiIdtScoreValueDto;
import com.guodi.model.entity.*;
import com.guodi.model.mapper.IdtScoreValueMapper;
import com.guodi.model.service.*;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @描述：指标得分值表服务类
 * @作者: lzy
 * @日期: 2023-04-03
 */
@Service
public class IdtScoreValueServiceImpl extends ServiceImpl<IdtScoreValueMapper, IdtScoreValue> implements IIdtScoreValueService {

    @Resource
    private IdtScoreValueMapper idtScoreValueMapper;
    @Resource
    private IIdtIndicatorsTypeService iIdtIndicatorsTypeService;
    @Resource
    private IIdtIndicatorsDirService idtIndicatorsDirService;
    @Resource
    private IIdtFillTaskScoreService iIdtFillTaskScoreService;

    private DecimalFormat df = new DecimalFormat("#.00");


    @Override
    public Map getDataListByYearAndCode(IdtScoreValue idtScoreValue, String code) {
        //获取根据编码获取体系类型
        IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(code, String.valueOf(idtScoreValue.getYear()), idtScoreValue.getDivisionCode());
        if (null == one) {
            return null;
        }
        Map map = new HashMap();
        map.put("parent_id", one.getId());
        List<IdtIndicatorsDir> dirs = idtIndicatorsDirService.listByMap(map);
        if (CollectionUtils.isEmpty(dirs)) {
            return null;
        }
//        Map<String,List<String>> dirToIds = new LinkedHashMap<>();
//        for(IdtIndicatorsDir dir : dirs){
//            List<IdtIndicatorsDir> allByParentId = idtIndicatorsDirService.getAllByParentId(dir.getId(), null);
//            List<String> idtIds = allByParentId.stream().filter(x -> x.getType() == 2).map(IdtIndicatorsDir::getIndicatorsId).collect(Collectors.toList());
//            dirToIds.put(dir.getId(),idtIds);
//        }

        List<MapDivision> mapDivisions = idtScoreValueMapper.listDivisionByCode(idtScoreValue.getDivisionCode());
        List<ApiDivisionToScoreValueDto> result = new ArrayList<>();
        for (MapDivision division : mapDivisions) {
            List<ApiIdtScoreValueDto> list = scoreListByYearAndCode(dirs, division, idtScoreValue.getYear());
            double sum = list.stream().mapToDouble(x -> x.getScoreValue() == null ? 0D : x.getScoreValue()).sum();
            ApiDivisionToScoreValueDto dto = new ApiDivisionToScoreValueDto();
            dto.setParentCode(division.getParentCode());
            dto.setDivisionCode(division.getCode());
            dto.setDivisionName(division.getName());
            dto.setValues(list);
            //截取判断,保留两位小数
            String sumStr = sum + "";
            Integer xsdInt = sumStr.length() - (sumStr.indexOf(".") + 1);
            if (xsdInt > 3) {
                BigDecimal two1 = new BigDecimal(sum);
                sum = two1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            }
            dto.setTotalValue(sum);
            result.add(dto);
        }
        List<ApiDivisionToScoreValueDto> parentDtos = result.stream().filter(d -> Objects.equals(idtScoreValue.getDivisionCode(), d.getDivisionCode())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(parentDtos)) {
            return null;
        }
        ApiDivisionToScoreValueDto parentDto = parentDtos.get(0);
        recursiveData(parentDto, result);
        Map resultMap = new HashMap();
        //列表数据
        resultMap.put("scorelist", parentDto.getChildren());

        //平均分数据
        List<Map<String, Object>> avgList = new ArrayList<>();
        //优秀排名
        List<Map<String, Object>> orderList = new ArrayList<>();
        for (IdtIndicatorsDir dir : dirs) {
            Map<String, Object> map1 = new HashMap<>();
            Map<String, Object> map2 = new HashMap<>();

            List<ApiIdtScoreValueDto> list = new ArrayList<>();
            for (ApiDivisionToScoreValueDto dto : parentDto.getChildren()) {
                for (ApiIdtScoreValueDto dto1 : dto.getValues()) {
                    if (dto1.getName().equals(dir.getName())) {
                        ApiIdtScoreValueDto valueDto = new ApiIdtScoreValueDto();
                        valueDto.setDivisionCode(dto1.getDivisionCode());
                        valueDto.setDivisionName(dto1.getDivisionName());
                        valueDto.setScoreValue(dto1.getScoreValue());
                        list.add(valueDto);
                    }
                }
            }


            map1.put("name", dir.getName());
            Double avg = list.stream().mapToDouble(x -> x.getScoreValue() == null ? 0D : x.getScoreValue()).average().getAsDouble();
            map1.put("avg", Double.valueOf(df.format(avg)));
            map1.put("total", Double.valueOf(df.format(avg)));
            map1.put("areaList", list);
            avgList.add(map1);

            //排序列表
            List<ApiIdtScoreValueDto> sList = list.stream().sorted(Comparator.comparingDouble(ApiIdtScoreValueDto::getScoreValue).reversed()).collect(Collectors.toList());
            Double scoreValue = sList.get(sList.size() > 4 ? 4 : sList.size()).getScoreValue();
            List<ApiIdtScoreValueDto> collect = sList.stream().filter(x -> x.getScoreValue() >= scoreValue).collect(Collectors.toList());
            map2.put("name", dir.getName());
            map2.put("scoreValue", Double.valueOf(df.format(scoreValue)));
            map2.put("area", collect.stream().map(ApiIdtScoreValueDto::getDivisionName).collect(Collectors.joining("、")));
            orderList.add(map2);
        }
        resultMap.put("avgList", avgList);
        resultMap.put("orderList", orderList);
        return resultMap;
    }

    private void recursiveData(ApiDivisionToScoreValueDto parentCode, List<ApiDivisionToScoreValueDto> allList) {
        List<ApiDivisionToScoreValueDto> childList = allList.stream().filter(p -> p.getParentCode().equals(parentCode.getDivisionCode())).collect(Collectors.toList());
        parentCode.setChildren(childList);
        for (ApiDivisionToScoreValueDto child : childList) {
            recursiveData(child, allList);
        }
    }

    /**
     * @描述:查询各个出得分值
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/4/4 9:58
     **/
    private List<ApiIdtScoreValueDto> scoreListByYearAndCode(List<IdtIndicatorsDir> treeList, MapDivision division, Integer year) {
        LambdaQueryWrapper<IdtFillTaskScore> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IdtFillTaskScore::getYear, String.valueOf(year));
        wrapper.eq(IdtFillTaskScore::getDivisionCode, division.getCode());
        List<IdtFillTaskScore> scoreList = this.iIdtFillTaskScoreService.list(wrapper);
        Map<String, IdtFillTaskScore> typeCollect = scoreList.stream().collect(Collectors.toMap(e -> e.getType(), e -> e, (e1, e2) -> e2));

        List<ApiIdtScoreValueDto> result = new ArrayList<>();
        for (IdtIndicatorsDir dir : treeList) {

            ApiIdtScoreValueDto dto = new ApiIdtScoreValueDto();
            dto.setName(dir.getName());
            dto.setDivisionCode(division.getCode());
            dto.setDivisionName(division.getName());
            dto.setYear(String.valueOf(year));
            dto.setScoreValue(typeCollect.get(dir.getName()) == null ? 0D : Double.valueOf(typeCollect.get(dir.getName()).getScore()));

            result.add(dto);
        }
        return result;
    }
}
